package service

import (
	"context"
	"errors"
	"fmt"
	"time"
	__ "user-srv/basic/proto"
	"user-srv/handler/dao"
)

// CheckIn 处理每日签到
func (s *Server) CheckIn(_ context.Context, in *__.CheckInReq) (*__.CheckInResp, error) {
	// 调用DAO层方法执行签到逻辑
	checkIn, i, err := dao.CheckIn(in)
	if err != nil {
		return nil, err
	}
	if err != nil {
		return &__.CheckInResp{
			Success:        false,
			Message:        err.Error(),
			ContinuousDays: 0,
			PointsAwarded:  0,
		}, nil
	}

	return &__.CheckInResp{
		Success:        true,
		ContinuousDays: int32(checkIn),
		PointsAwarded:  int32(i),
		Message:        "签到成功",
	}, nil
}

// GetCheckInList 获取签到列表
func (s *Server) GetCheckInList(_ context.Context, in *__.GetCheckInListReq) (*__.GetCheckInListResp, error) {
	if in.UserId <= 0 {
		return nil, errors.New("无效的用户ID")
	}
	// 处理默认年月（当前年月）
	now := time.Now()
	year := int(in.Year)
	month := int(in.Month)
	//day := int(in.Day)

	if year <= 0 {
		year = now.Year()
	}
	if month <= 0 || month > 12 {
		month = int(now.Month())
	}

	// 调用DAO层方法获取签到记录
	checkInMap, err := dao.GetCheckInList(in)
	if err != nil {
		// 改进错误处理：记录日志并返回友好的错误信息
		// log.Printf("获取用户%d在%d年%d月的签到记录失败: %v", req.UserId, year, month, err)
		return &__.GetCheckInListResp{
			Year:              int32(year),
			Month:             int32(month),
			CheckinStatusList: nil,
			ContinuousDays:    0,
		}, nil
	}

	// 转换为Proto定义的响应格式
	var statusList []*__.DailyCheckInStatus
	for day, checkedIn := range checkInMap {
		statusList = append(statusList, &__.DailyCheckInStatus{
			Day:       int32(day),
			CheckedIn: checkedIn.CheckedIn,
			IsMakeup:  false, // 根据实际需求设置
		})
	}

	return &__.GetCheckInListResp{
		Year:              int32(year),
		Month:             int32(month),
		CheckinStatusList: statusList,
		ContinuousDays:    0, // 根据实际需求设置连续签到天数
	}, nil
}

// MakeUpCheckIn 处理补签
func (s *Server) MakeUpCheckIn(_ context.Context, in *__.MakeUpCheckInReq) (*__.MakeUpCheckInResp, error) {
	if in.UserId <= 0 {
		return nil, errors.New("无效的用户ID")
	}

	if in.Date == "" {
		return nil, errors.New("请指定补签日期")
	}

	// 解析日期
	date, err := time.Parse("2006-01-02", in.Date)
	if err != nil {
		return nil, errors.New("日期格式错误，应为YYYY-MM-DD")
	}

	// 调用DAO层方法执行补签
	success, points, err := dao.MakeUpCheckIn(in.UserId, date)
	if err != nil {
		return &__.MakeUpCheckInResp{
			Success:       false,
			Message:       err.Error(),
			PointsAwarded: 0,
		}, nil
	}

	if success {
		return &__.MakeUpCheckInResp{
			Success:       true,
			Message:       "补签成功",
			PointsAwarded: int32(points),
		}, nil
	}

	return &__.MakeUpCheckInResp{
		Success:       false,
		Message:       "补签失败，可能已签到或超过补签期限",
		PointsAwarded: 0,
	}, nil
}

// GetCheckInInfo 获取签到信息
func (s *Server) GetCheckInInfo(_ context.Context, in *__.GetCheckInInfoReq) (*__.GetCheckInInfoResp, error) {
	isChecked, isBroken, continuousDays, err := dao.GetCheckInStatus(in.UserId, time.Now())
	if err != nil {
		return nil, err
	}

	// 构建详细的状态信息
	checkInStatus := ""
	if isChecked {
		checkInStatus = "今天已经签到"
	} else {
		checkInStatus = "今天尚未签到"
	}

	breakStatus := ""
	if isBroken {
		breakStatus = "已断签"
	} else {
		breakStatus = "连续签到中"
	}

	fmt.Printf("用户%d签到状态: %s, 断签状态: %s, 连续签到%d天\n",
		in.UserId, checkInStatus, breakStatus, continuousDays)

	fmt.Printf("当前连续签到%d天\n", continuousDays)
	return &__.GetCheckInInfoResp{
		CheckInStatus: checkInStatus, // 今日签到状态
		BreakStatus:   breakStatus,   // 断签状态
		Message:       fmt.Sprintf("连续签到%d天", continuousDays),
	}, nil
}
